<template>
  <div id="workflow">
    <div class="tree">
      <el-button
        type="success"
        size="small"
        plain
        @click="addWorkTreeVisible = true"
        style="margin-bottom:20px"
      >添加</el-button>
      <el-button
        type="primary"
        size="small"
        plain
        @click="edit"
        style="margin-bottom:20px"
        :disabled="isDisable"
      >修改</el-button>
      <el-button
        type="warning"
        size="small"
        plain
        @click="authorize"
        style="margin-bottom:20px"
        :disabled="isDisable"
      >授权</el-button>
      <el-popover placement="top" width="160" v-model="typeVisible">
        <p>确定要删除吗？</p>
        <div style="text-align: right; margin: 0">
          <el-button size="mini" type="text" @click="typeVisible = false">取消</el-button>
          <el-button type="primary" size="mini" @click="typeDelete">确定</el-button>
        </div>
        <el-button slot="reference" type="danger" plain size="small" :disabled="isDisable">删除</el-button>
      </el-popover>
      <!-- 组织树 -->
      <el-tree
        :highlight-current="true"
        ref="orgTree"
        node-key="id"
        :data="folderList"
        :props="defaultProps"
        @node-click="handleNodeClick"
      ></el-tree>
    </div>
    <div class="table">
      <div class="workflow-table">
        <el-table :data="tableData" border style="width: 100%">
          <el-table-column prop="name" label="文件名" width="180"></el-table-column>
          <el-table-column prop="creator" label="创建人"></el-table-column>
          <el-table-column prop="createTime" label="创建时间"></el-table-column>
          <el-table-column fixed="right" label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.suffixType=='doc'||scope.row.suffixType=='xlsx'||scope.row.suffixType=='xls'||scope.row.suffixType=='pdf'||scope.row.suffixType=='docx'"
                type="text"
                size="small"
                @click.native="handleEdit(scope.row)"
              >预览</el-button>
              <el-button type="text" size="small" @click.native="handleDownLoad(scope.row)">下载</el-button>
              <el-button type="text" size="small" @click.native="handleCancel(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pull-right paddingTop">
          <el-pagination
            background
            @current-change="handleCurrentChange"
            :page-size="10"
            :current-page="this.pageNo"
            :total="this.total"
            layout="prev, pager, next"
          ></el-pagination>
        </div>
      </div>
    </div>
    <el-dialog title="添加文件夹" :visible.sync="addWorkTreeVisible" @open="beforeOpenTree">
      <el-form :model="typeform" label-width="120px">
        <el-form-item label="文件夹名称" :label-width="formLabelWidth">
          <el-input v-model="typeform.name"></el-input>
        </el-form-item>
        <el-form-item label="排序" :label-width="formLabelWidth">
          <el-input v-model="typeform.num"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addWorkTreeVisible = false">取 消</el-button>
        <el-button type="primary" @click="addWorkTree" :disabled="isUpdate">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="修改文件夹" :visible.sync="editFolderVisible">
      <el-form :model="typeform">
        <el-form-item label="文件夹名称" :label-width="formLabelWidth">
          <el-input v-model="typeform.name"></el-input>
        </el-form-item>
        <el-form-item label="排序" :label-width="formLabelWidth">
          <el-input v-model="typeform.num"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFolderVisible = false">取 消</el-button>
        <el-button type="primary" @click="editFolder">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="授权" :visible.sync="authorizeVisible" @open="beforeOpenTree">
      <el-form :model="typeform">
        <!-- 授权人员树 -->
        <el-tree
          :props="props"
          :load="loadNode"
          lazy
          show-checkbox
          ref="peopleTree"
          node-key="id"
          @check-change="handleCheckChange"
        ></el-tree>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleAuthorizeCancle">取 消</el-button>
        <el-button type="primary" @click="handleAuthorize">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      //文件夹开始
      folderList: [{ name: "知识库文件夹", items: [] }],
      folderId: "",
      tableData: [],
      pageSize: 10,
      pageNo: 1,
      total: 0,
      defaultProps: {
        children: "items",
        label: "name"
      },
      formLabelWidth: "100px",
      addWorkTreeVisible: false,
      editFolderVisible: false,
      authorizeVisible: false,
      typeVisible: false,
      typeform: {
        name: "",
        num: ""
      },
      folderName: "",
      orgList: [],
      props: {
        label: "name",
        children: "items",
        isLeaf: "leaf"
      },
      count: 1,
      department: [],
      peopleList: [],
      checkedId: [],
      orgId:[],
      isDisable: true,
      authorizeList: [],
      isUpdate: false
      //文件夹结束
    };
  },
  computed: {},
  mounted() {
    this.getFolderList();
    this.getOrgList();
  },
  methods: {
    //请求获取文件夹列表开始
    getFolderList() {
      this.http.post("/api/document/folder/tree").then(res => {
        // console.log("获取所有文件夹");
        if (res.data.data) {
          let tempList = res.data.data;
          this.folderList[0].items = res.data.data;
        }
      });
    },
    //请求获取文件夹列表结束

    handleCurrentChange(val) {
      this.pageNo = val;
      this.getDocumentList(this.folderId);
      // console.log("分页");
    },

    getDocumentList(id) {
      //请求对应文件夹的文件
      if (id) {
        let json = {
          folderId: id,
          orgId: "",
          creator: "",
          startTime: "",
          endTime: "",
          queryType: 2,
          userId: "",
          name: "", //文档名称
          // labelId: this.state.labelId,//标签id
          all: false,
          size: this.pageSize,
          current: this.pageNo,
          desc: "create_time"
        };
        this.http.post("/api/document/list", json).then(res => {
          console.log(res);
          this.tableData = res.data.data.records;
          this.total = res.data.data.total;
        });
      }

      // this.http
      // .post("/api/document/query",{
      //   P_ORDER:"DESC",
      //   P_SORT:"create_time",
      //   Q_COLUMN:"AND_folder_id_EQ",
      //   Q_VALUE:id,
      //   P_NO:this.pageNo,
      //   P_SIZE:this.pageSize
      // })
      // .then(res=>{
      //   this.tableData = res.data.rows;
      //   this.total = res.data.records;
      // });
    },
    addWorkTree() {
      //文件夹开始
      let _this = this;
      this.isUpdate = true;
      if (
        this.typeform.name &&
        this.typeform.name != " " &&
        this.typeform.num &&
        this.typeform.num != " " &&
        !isNaN(this.typeform.num)
      ) {
        this.http
          .post("/api/document/folder/save", {
            parentId: this.folderId,
            name: this.typeform.name,
            sort: this.typeform.num
          })
          .then(res => {
            if (res.data.code == 201) {
              console.log("201");
              this.$message.error(res.data.msg);
              this.isUpdate = false;
            } else {
              this.isUpdate = true;
              _this.getFolderList();
              console.log("添加文件夹成功");
              this.addWorkTreeVisible = false;
              this.folderId = "";
            }
          });
      }
      if (!this.typeform.name || this.typeform.name == " ") {
        this.$message.error("请输入文件夹名称");
      }
      if (
        !this.typeform.num ||
        this.typeform.num == " " ||
        isNaN(this.typeform.num)
      ) {
        this.$message.error("请输入排序数字");
        this.isUpdate = false;
      }
      //文件夹结束
    },
    beforeOpenTree() {
      this.typeform.name = "";
      this.typeform.num = "";
      this.isUpdate = false;
    },
    typeDelete() {
      //文件夹开始
      let _this = this;
      if (this.folderId) {
        this.http
          .post("/api/document/folder/deleteBatchIds", {
            ids: this.folderId
          })
          .then(res => {
            console.log("删除成功");
            _this.getFolderList();
            this.typeVisible = false;
            this.folderId = "";
            this.typeform.name = "";
            this.typeform.num = "";
          });
      } else {
        this.typeVisible = false;
        this.$message.error("请选择需要删除的文件夹");
      }
      //文件夹结束
    },
    //修改文件夹开始
    edit() {
      if (this.folderId) {
        this.editFolderVisible = true;
        this.typeform.name = this.folderName;
      } else {
        this.$message.error("请选择需要修改的文件夹");
      }
    },
    editFolder() {
      let _this = this;
      if (this.folderId) {
        if (
          this.typeform.name &&
          this.typeform.name != " " &&
          this.typeform.num &&
          this.typeform.num != " " &&
          !isNaN(this.typeform.num)
        ) {
          this.http
            .post("/api/document/folder/save", {
              id: this.folderId,
              name: this.typeform.name,
              sort: this.typeform.num
            })
            .then(res => {
              if (res.data.code == 201) {
                console.log("201");
                this.$message.error(res.data.msg);
              } else {
                _this.getFolderList();
                console.log("修改文件夹成功");
                this.editFolderVisible = false;
                this.folderId = "";
              }
            });
        }
        if (!this.typeform.name || this.typeform.name == " ") {
          this.$message.error("请输入文件夹名称");
        }
        if (
          !this.typeform.num ||
          this.typeform.num == " " ||
          isNaN(this.typeform.num)
        ) {
          this.$message.error("请输入排序数字");
        }
      } else {
        this.$message.error("请选择需要修改的文件夹");
      }
    },

    //修改文件夹结束
    //授权开始
    authorize() {
      if (this.folderId) {
        this.authorizeVisible = true;
        console.log("开始授权啦~");
        //获取之前的授权信息并进行渲染
        // console.log(this.folderId);
        this.http
          .post("/api/document/folder/getFolderUserId", {
            folderId: this.folderId
          })
          .then(res => {
            this.checkedId = res.data.data;
            this.$refs.peopleTree.setCheckedKeys(this.checkedId);
          });
      } else {
        this.$message.error("请选择需要授权的文件夹");
      }
    },
    //授权结束
    handleAuthorizeCancle() {
      this.authorizeVisible = false;
      this.checkedId = [];
    },
    //获取组织架构开始
    getOrgList() {
      var _this = this;
      this.http
        .post("/api/org/orgNodeList", {
          type: "org",
        })
        .then(res => {
          let data = res.data.data;
          data.map(item => {
            item.disabled = true;
          });
          this.orgList = data;
        })
        .catch(err => {});
    },

    bianliId(data){
      data.map(item => {
        this.orgId.push(item.id);
        if(item.items.length > 0){
          this.bianliId(items)
        }
      })
    },
    fanbianliId(data){
      data.map(item => {
        if (this.orgId.includes(data.id)) {
          this.orgId = this.orgId.filter(item => {
            if (item != data.id) {
              return true;
            }
          });
        }
        if(item.items.length > 0){
          this.bianliId(items)
        }
      })
    },

    //人员列表获取开始
    handleCheckChange(data, checked, indeterminate) {
      console.log(data, checked, indeterminate);
      if (checked) {
        if(data.createTime){
          this.orgId.push(data.id);
          if(data.items.length > 0){
            this.bianliId(data.items);
          }
        }
        else{
          this.checkedId.push(data.id);
        }
      } else {
        if(data.createTime){
          if (this.orgId.includes(data.id)) {
            this.orgId = this.orgId.filter(item => {
              if (item != data.id) {
                return true;
              }
            });
          }
          if(data.items.length > 0){
            this.fanbianliId(data.items);
          }
        }
        else{
          if (this.checkedId.includes(data.id)) {
            this.checkedId = this.checkedId.filter(item => {
              if (item != data.id) {
                return true;
              }
            });
          }
        }
      }
      console.log(this.orgId);
      console.log(this.checkedId);
    },
    handleNodeClick(data) {
      // console.log(data);
      let _this = this;
      this.folderId = data.id;
      this.pageNo = 1;
      this.typeform.name = data.name;
      this.folderName = data.name;
      this.typeform.num = data.sort;
      _this.getDocumentList(this.folderId);
      if (data.name == "知识库文件夹") {
        this.isDisable = true;
        this.tableData = [];
        this.total = 0;
      } else {
        this.isDisable = false;
      }
      this.folderId = data.id;
    },
    loadNode(node, resolve) {
      this.peopleList = [];
      //一级获取分公司列表
      if (node.level === 0) {
        this.authorizeList = [
          { name: "公司", items: this.orgList, disabled: true }
        ];
        return resolve(this.authorizeList);
      }
      //获取部门列表及分公司人员
      // console.log(node);
      if (node.data.items.length > 0) {
        this.department = node.data.items;
        this.http
          .post("/api/user/getUserList", { orgId: node.data.id })
          .then(res => {
            let people = res.data.data.records;
            people.map(e => {
              let json = {
                name: e.userName,
                items: [],
                id: e.id,
                leaf: true
              };
              this.department.push(json);
            });

            return resolve(this.department);
          });
      } else if (node.data.id) {
        this.http
          .post("/api/user/getUserList", { orgId: node.data.id })
          .then(res => {
            let people = res.data.data.records;
            people.map(e => {
              let json = {
                name: e.userName,
                items: [],
                id: e.id,
                leaf: true
              };
              this.peopleList.push(json);
            });
            return resolve(this.peopleList);
          });
      } else {
        return resolve([]);
      }
    },
    //人员列表获取结束
    handlePeopleList(arr) {
      var newArr = [];
      arr.map(e => {
        let json = {
          lable: e.userName,
          children: []
        };
        newArr.push(json);
      });
      return newArr;
    },
    handleAuthorize() {
      let userId = this.checkedId.join(",");
      let orgId = this.orgId.join(",");
      if (this.folderId) {
        this.http
          .post("/api/document/folder/user/grant", {
            folderId: this.folderId,
            userId,
            orgId
          })
          .then(res => {
            console.log("授权成功");
            this.authorizeVisible = false;
            // this.folderId = "";
            this.checkedId = []; //清空授权列表
          });
      } else {
        this.$message.error("请选择需要授权的文件夹");
      }
    },
    handleEdit(row) {
      let attachmentId = row.attachmentId;
      let suffixType = row.suffixType;
      let href = window.location.href.split("#")[0];
      if (suffixType == "pdf") {
        window.open(
          `${href}api/file/download2?attachmentId=${attachmentId}`,
          "_blank"
        );
      } else {
        window.open(`${href}#/document/${attachmentId}/${suffixType}`);
      }
    },
    handleDownLoad(row) {
      let attachmentId = row.attachmentId;
      let href = window.location.href.split("#")[0];
      window.open(
        `${href}api/file/download?attachmentId=${attachmentId}`,
        "_blank"
      );
    },
    handleCancel(row) {
      let _this = this;
      let id = row.id;
      this.$confirm("此操作将永久删除选中的数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.http
          .post("/api/document/delete", {
            id
          })
          .then(res => {
            _this.getDocumentList(this.folderId);
          });
      });
    }
  }
};
</script>
<style lang="scss">
#workflow {
  padding: 0 10px;
  height: 100%;
  .workflow-table {
    a {
      color: #409eff;
      text-decoration: none;
    }
    .paddingTop {
      padding-top: 20px;
    }
    .cell {
      text-align: center;
    }
  }
  .tree {
    height: 100%;
    width: 17%;
    float: left;
    overflow-x: auto;
    border-right: 1px solid #ccc;
    .el-button + .el-button {
      margin-left: 0;
    }
  }
  .table {
    padding-left: 2%;
    float: right;
    width: 83%;
  }
}
</style>


